<?php


namespace api\crm\controller;


use api\crm\model\CouponModel;
use api\crm\model\GetCardLogModel;
use api\crm\model\GoodsModel;
use api\crm\model\OrderGoodsModel;
use api\crm\model\OrderInfoModel;
use api\crm\model\UserModel;
use api\crm\model\WechatUserModel;
use app\admin\model\MemberCardInfoModel;
use cmf\controller\RestBaseController;
use think\Db;

class CouponController extends RestBaseController
{
    public function get_coupons()
    {
        $data = $this->request->param();
        $num = 10;
        $page = isset($data['page']) && $data['page'] ? $data['page'] : 1;
        $company_id = isset($data['company_id']) && $data['company_id'] ? $data['company_id'] : 0;
        $type = isset($data['type']) && $data['type'] ? $data['type'] : 0;
        $where = [];
        $where[] = ['company_id', '=', $company_id];
        //是否可以领取
        $where[] = ['is_receive', '=', 1];
        //普通优惠券
        $where[] = ['type', '=', $type];
        //卡券状态
        $where[] = ['status', '=', 'CARD_STATUS_VERIFY_OK'];
        $list = CouponModel::where($where)
            ->order('create_time desc')
            ->paginate($num, false, ['page' => $page])
            ->each(function ($item) {
                if ($item['begin_timestamp']) {
                    $item['begin_timestamp'] = date('Y年m月d日', $item['begin_timestamp']);
                }
                if ($item['end_timestamp']) {
                    $item['end_timestamp'] = date('Y年m月d日', $item['end_timestamp']);
                }

                return $item;
            });
        $this->success('获取优惠券', $list);
    }

    public function get_coupon_by_id($id)
    {
        $data = $this->request->param();
        $where[] = ['is_receive', '=', 1];
        $where[] = ['status', '=', 'CARD_STATUS_VERIFY_OK'];
        $coupon_info = CouponModel::where($where)->get($id);
        if (empty($coupon_info)) {
            $this->error('数据异常');
        } else {
            if ($coupon_info['begin_timestamp']) {
                $coupon_info['begin_timestamp'] = date('Y年m月d日', $coupon_info['begin_timestamp']);
            }
            if ($coupon_info['end_timestamp']) {
                $coupon_info['end_timestamp'] = date('Y年m月d日', $coupon_info['end_timestamp']);
            }
            if ($coupon_info['use_condition']) {
                $coupon_info['goods_list'] = GoodsModel::where(['is_on_sale' => 1])
                    ->order('create_time desc')
                    ->where('id', 'in', $coupon_info['use_condition'])->all();
            }
            $this->success('', $coupon_info);
        }
    }

    public function receive_coupon($id)
    {
        $data = $this->request->param();
        $where[] = ['is_receive', '=', 1];
        $where[] = ['status', '=', 'CARD_STATUS_VERIFY_OK'];
        $coupon_info = CouponModel::where($where)->get($id);
        if (empty($coupon_info)) {
            $this->error('数据异常');
        } else {
            $param['company_id'] = $coupon_info['company_id'];
            $param['url'] = $data['url'];
            $param['card_list'] = [
                ['card_id' => $coupon_info['card_id'],
                    'outer_id' => $coupon_info['id']]
            ];
            $result = hook('html_send_card', $param);
            $this->success('', $result);
        }
    }

    public function receive_member_card($id)
    {
        $data = $this->request->param();

        $coupon_info = MemberCardInfoModel::where(['company_id' => $id, 'is_on_sale' => 1])->order('create_time desc')->limit(1)->find();
        if (empty($coupon_info)) {
            $this->error('数据异常'.$id);
        } else {
            $param['company_id'] = $coupon_info['company_id'];
            $param['url'] = $data['url'];
            $param['card_list'] = [
                ['card_id' => $coupon_info['card_id'],
                    'outer_id' => $coupon_info['id']]
            ];

            $result = hook('html_send_card', $param);
            $this->success('', $result);
        }
    }

    public function get_user_coupon_list()
    {
        $data = $this->request->param();
        $page = isset($data['page']) && $data['page'] ? $data['page'] : 1;
        $num = 10;
        $user_id = $this->getWechatUserId();
        $user_info = WechatUserModel::get($user_id);
        $cards_ids = CouponModel::where(['company_id' => $user_info['company_id'], 'status' => 'CARD_STATUS_VERIFY_OK'])->column('card_id');
        $list = GetCardLogModel::with('coupon_info')
            ->where(['openid' => $user_info['openid']])->where('card_id', 'in', $cards_ids)
            ->paginate($num, false, ['page' => $page])->each(function ($item) {
                if ($item['create_time']) {
                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                }
                if ($item['coupon_info']['begin_timestamp']) {
                    $item['coupon_info']['begin_timestamp'] = date('Y年m月d日', $item['coupon_info']['begin_timestamp']);
                }
                if ($item['coupon_info']['end_timestamp']) {
                    $item['coupon_info']['end_timestamp'] = date('Y年m月d日', $item['coupon_info']['end_timestamp']);
                }
                return $item;
            });
        $this->success('我的优惠券', $list);
    }

    public function get_can_use_coupon_list()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $user_info = WechatUserModel::get($user_id);
        $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
        $order_info = OrderInfoModel::with('order_goods_list')->where('order_sn', $order_sn)->find();
        if (empty($order_info)) {
            $this->error('订单信息异常');
        }
        $goods_ids = OrderGoodsModel::where('order_id', $order_info['id'])->column('goods_id');
        $card_ids = [];
        foreach ($goods_ids as $value) {
            $where[] = ['', 'exp', Db::raw("FIND_IN_SET($value, use_condition)")];
            $current_card_ids = CouponModel::where($where)->column('card_id');
            $card_ids = array_merge($card_ids, $current_card_ids);
        }
        $order_id = $order_info['id'];
        $card_ids = array_unique($card_ids);
        $my_coupon = GetCardLogModel::with('coupon_info')->where(['openid' => $user_info['openid'], 'card_id' => $card_ids, 'status' => 0])->select();
        foreach ($my_coupon as $key => $value) {
            $coupon_info = $value['coupon_info'];
            if ($coupon_info['begin_timestamp']) {
                $my_coupon[$key]['coupon_info']['begin_timestamp'] = date('Y年m月d日', $coupon_info['begin_timestamp']);
            }
            if ($coupon_info['end_timestamp']) {
                $my_coupon[$key]['coupon_info']['end_timestamp'] = date('Y年m月d日', $coupon_info['end_timestamp']);
            }
            $use_condition = $coupon_info['use_condition'];
            switch ($coupon_info['coupon_type']) {
                case 'CASH':
                    $total_price = OrderGoodsModel::where('goods_id', 'in', $use_condition)->where('order_id', $order_id)
                        ->sum('total_price');
                    if ($total_price > $coupon_info['least_cost']) {
                        $my_coupon[$key]['coupon_money'] = $coupon_info['reduce_cost'];
                    }
                    break;
                case 'DISCOUNT':
                    $total_price = OrderGoodsModel::where('goods_id', 'in', $use_condition)->where('order_id', $order_id)
                        ->sum('total_price');
                    $my_coupon[$key]['coupon_money'] = $coupon_info['discount'] * $total_price / 100;
                    break;
                case 'GIFT':
                    //兑换券 默认免除价格最高的意见商品
                    $order_goods = OrderGoodsModel::where('goods_id', 'in', $use_condition)->where('order_id', $order_id)
                        ->order('total_price desc')->limit(1)->find();
                    $my_coupon[$key]['coupon_money'] = $order_goods['goods_price'];
                    break;
            }
        }
        $this->success('获取可用优惠券', $my_coupon);
    }

    public function get_member_list()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $user_info = WechatUserModel::get($user_id);
        $list = MemberCardInfoModel::where([
            'company_id' => $user_info['company_id'],
            'is_on_sale' => 1])->find();
        $this->success('获取会员卡列表', $list);
    }

}
